package com.shrw.duke.bluetoothheartrate.ui;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.WindowManager;

import com.shrw.duke.bluetoothheartrate.R;
import com.shrw.duke.bluetoothheartrate.adapter.BaseAdapter;
import com.shrw.duke.bluetoothheartrate.entity.RateEntity;
import com.shrw.duke.bluetoothheartrate.entity.StateEntity;
import com.shrw.duke.bluetoothheartrate.utils.Convert;
import com.shrw.duke.bluetoothheartrate.utils.HexUtil;

import java.util.Arrays;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;

public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
    public static final String _CRNO_1 = "C7";
    public static final String _CRNO_2 = "1400";
    public static final String _LABEL_TYPE = "F0";
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private RecyclerView mRecyclerView;
    private BaseAdapter mAdapter;

    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        initToolsBar();
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onStop() {
        super.onStop();
//        ViseBle.getInstance().clear();
    }

    private void initView() {
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mSwipeRefreshLayout.setOnRefreshListener(this);

        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mAdapter = new BaseAdapter(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            requestPermissions(new String[]{ACCESS_COARSE_LOCATION}, 1);
        } else {
            bluetooth();
        }


    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                bluetooth();
                break;
        }
    }

    private void bluetooth() {
        BluetoothManager bluetoothManager = (BluetoothManager) this.mContext.getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            bluetoothAdapter.enable();
        }
        bluetoothAdapter.startLeScan(new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
//                if (Math.abs(rssi)<70){
                    if (mSwipeRefreshLayout.isRefreshing()){
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
//                            String record = HexUtil.encodeHexStr(scanRecord);
//                if (device.getAddress().equals("88:99:88:FE:70:44")){
                    String[] recordArray = Convert.toHexStringArray(scanRecord, scanRecord.length);
                    StringBuilder record = Convert.toHexString(scanRecord, scanRecord.length);
                    String CRNO_1 = recordArray[5];
                    String label_type = recordArray[7];
                    StringBuilder CRNO_2 = new StringBuilder();
                    CRNO_2.append(recordArray[16]);
                    CRNO_2.append(recordArray[17]);

                    if (_CRNO_1.equals(CRNO_1)
                            && _CRNO_2.equals(CRNO_2.toString())
                            && _LABEL_TYPE.equals(label_type)) {
                        String label = record.substring(18,29);
//                        String rateStr = record.substring(38,61);
                        char[] stateArray = Convert.hexString2binaryString(recordArray[18]).toCharArray();
                        RateEntity rateEntity = new RateEntity();
                        rateEntity.setName(label);
                        rateEntity.setAddress(device.getAddress());
                        rateEntity.setRecord(record.toString());
                        rateEntity.setRssi(rssi);
                        rateEntity.setStateEntity(new StateEntity(stateArray[0],stateArray[1],stateArray[2],stateArray[3],
                                stateArray[4],stateArray[5],stateArray[6],stateArray[7]));
                        rateEntity.setRate(recordArray[20]);
                        rateEntity.setVolt(recordArray[19]);
                        rateEntity.setLf_Times(recordArray[21]);
                        rateEntity.setNrf_Times(recordArray[22]);
                        rateEntity.setAID_STR1_ActID(recordArray[23]+recordArray[24]);
                        rateEntity.setAID_STR1_Rssi(recordArray[25]);
                        rateEntity.setAID_STR2_ActID(recordArray[26]+recordArray[27]);
                        rateEntity.setAID_STR2_Rssi(recordArray[28]+recordArray[27]);
                        rateEntity.setAID_STR3_ActID(recordArray[29]+recordArray[30]);
                        int index = mAdapter.addItem(rateEntity);

                        if (Math.abs(rssi)<=50){
                            if (!mAdapter.isShowPopup()){
                                if (index == -1){
                                    mAdapter.showPopup(mAdapter.getItemCount()-1,mRecyclerView);
                                    mRecyclerView.scrollToPosition(mAdapter.getItemCount()-1);
                                }else {
                                    mAdapter.showPopup(index,mRecyclerView);
                                    mRecyclerView.scrollToPosition(index);
                                }


                            }

                        }

//                        Log.d("onLeScan1", Arrays.toString(recordArray));
//                        Log.d("onLeScan1", "公司编号：" + recordArray[5]);
                    }
//                    Log.d("onLeScan2", Arrays.toString(recordArray));
//                    Log.d("onLeScan2", "公司编号：" + recordArray[5]);
//                }

            }
        });
    }

    private void initToolsBar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_recycler_view);
        setSupportActionBar(toolbar);
    }

    @Override
    public void onRefresh() {
        mAdapter.clearAll();
    }
}
